import Fly from './environment/fly';
import config from './config';
import wxAuth from './wxAuth';
import keys from './keys';
let fly = new Fly();
let authorization = '';
/**
 * 拦截请求
 */
fly.interceptors.request.use(async (request,promise) =>{
    // {
    //     headers:{}, //http请求头，
    //     baseURL:"", //请求基地址
    //     timeout:0,//超时时间，为0时则无超时限制
    //     //是否自动将Content-Type为“application/json”的响应数据转化为JSON对象，默认为true
    //     parseJson:true,
    //     withCredentials:false //跨域时是否发送cookie
    //   }
    //请求配置项
    //服务器存储的登录授权信息
    let authorization = mpvue.getStorageSync(keys.Authorization);
    //如果信息存在
    if(authorization){
        request.headers[keys.Authorization] = authorization;
        return request;
    }else{
        //加锁
        fly.lock();
        //如果
        let code = await wxAuth.login();
        if(typeof code == 'string'){
            //重新登录
            return new Fly().get('/user/login',{code : code},{baseURL:config.baseURL}).then((res)=>{
                if(res.data.token){
                    //返回授权码
                    authorization = res.data.token;
                    request.headers[keys.Authorization] = authorization;
                    mpvue.setStorageSync(keys.Authorization,authorization);
                }else{
                    //登录失败
                }
            }).
            then(()=>{
                fly.unlock();
                //如果不是调用登录接口
                if(!request.url.endsWith('/user/login')){
                    return request;
                }
            }).
            catch((err)=>{
                //请求出错，可能是网络错误
                console.log('login error 1:',err);
                fly.unlock();
            });
        }else{
            fly.unlock();
        }
    }
});

/**
 * 拦截响应
 */
fly.interceptors.response.use(async (response,promise) => {
    console.log('fly拦截器响应：interceptors.response',response);
    if(response.data.tokenExpired){
        //判断token是否失效
        fly.lock();
        let code = await wxAuth.login();
        if(typeof code == 'string'){
            //重新获取token
            return new Fly().get('/user/login',{code : code},{baseURL:config.baseURL}).then((res)=>{
                if(res.data.token){
                    //保存token
                    authorization = res.data.token;
                    mpvue.setStorageSync(keys.Authorization,authorization);
                }else{
                    //登录失败
                }
            }).
            then(()=>{
                fly.unlock();
                return fly.request(response.request);
            }).
            catch(()=>{
                //发生网络异常
                console.log('login error 2:',err);
                fly.unlock();
            });
        }else{
            fly.unlock();
        }
    }else{
        return response.data;
    }
    
},(err)=>{
    console.log('网络错误',err);
    //网络错误：err的内容
    // {
    //     message:"Not Find 404", //错误消息
    //     status:404, //如果服务器可通，则为http请求状态码。网络异常时为0，网络超时为1
    //     request:{...}, //对应的请求信息
    //     response:{}, //响应信息
    //     engine:{}//请求使用的http engine(见下面文档),浏览器中为本次请求的XMLHttpRequest对象
    //   }
    mpvue.showToast({
        title : err.message,
        icon : 'none',
        duration : 200
    });
});

export default fly;